﻿using System.Web.Mvc;
using FlitBit.Core;

namespace FlitBit.Dto.ModelBinders
{
	public class DtoEnabledDefaultModelBinder : DefaultModelBinder
	{
		public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
		{
			var modelType = bindingContext.ModelType;
			if (modelType.IsAbstract)
			{
				var factory = FactoryProvider.Factory;
				if (factory.CanConstruct(modelType))
				{
					var finalType = factory.GetImplementationType(modelType);
					if (!finalType.IsAbstract)
					{
						var meta = ModelMetadataProviders.Current.GetMetadataForType(null, finalType);
						bindingContext.ModelMetadata = meta;
					}
				}
			}
			return base.BindModel(controllerContext, bindingContext);
		}
	}
}